//封装axios
import axios from 'axios'
import { useUserStore } from '@/stores/index.js'
import router from '@/router/index.js'
import { ElMessage } from 'element-plus'

const baseURL = 'http://big-event-vue-api-t.itheima.net'

const service = axios.create({
  baseURL,
  timeout: 100000
})
service.interceptors.request.use(
  (config) => {
    const userStore = useUserStore()
    if (userStore.token) {
      config.headers.Authorization = userStore.token
    }
    return config
  },
  (error) => Promise.reject(error)
)
service.interceptors.response.use(
  (res) => {
    if (res.data.code === 0) {
      return res
    }
    ElMessage.error({ message: res.data.message || '服务器异常' })
    return Promise.reject(res.data)
  },
  (error) => {
    //TODO 5.处理401错误
    ElMessage.error({ message: error.response.data.message || '服务器异常' })
    console.log(error)
    if (error.response?.status === 401) {
      router.push('/login').then((r) => r)
    }
    return Promise.reject(error)
  }
)
export default service
export { baseURL }
